<template>
  <TooltipProvider>
    <main
      v-show="!state.tempHide"
      class="text-base text-left !font-sans"
      style="color-scheme: dark"
    >
      <AppElementScanner v-if="!state.paused" />
      <AppElementDetail />
      <FloatToolbar />
      <AppToolbar />
    </main>
  </TooltipProvider>
</template>
<script setup lang="ts">
import { EL_ATTR_NAME } from '@root/src/utils/constant';
import { useAppProvider } from './app-plugin';
import AppElementDetail from './app/AppElementDetail.vue';
import FloatToolbar from './app/FloatToolbar.vue';
import AppElementScanner from './app/AppElementScanner.vue';
import AppToolbar from './app/AppToolbar.vue';
import { watch, onUnmounted, onMounted } from 'vue';
import { TooltipProvider } from 'radix-vue';
import { startTyping } from '../../../utils/helper';
import { emitter } from '@root/src/lib/mitt';
const { state } = useAppProvider();

watch(
  () => state.showGrid,
  (showGrid) => {
    if (showGrid) document.body.setAttribute(EL_ATTR_NAME.showGrid, '');
    else document.body.removeAttribute(EL_ATTR_NAME.showGrid);
  },
);

// 添加文本选择监听器
const addSelectionListener = () => {
  // 监听mouseup事件
  document.addEventListener('mouseup', handleTextSelection);
};

// 移除文本选择监听器
const removeSelectionListener = () => {
  document.removeEventListener('mouseup', handleTextSelection);
};

// 处理选中文本的事件
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const handleTextSelection = (event: any) => {
  // 获取事件目标
  const selection = window.getSelection();
  const selectedText = selection.toString().trim();

  // 检查事件目标是否在 #inspect-css-root 内
  const inspectRoot = document.getElementById('inspect-css-root');
  if (inspectRoot && inspectRoot.contains(event.target)) {
    // 如果事件目标在 #inspect-css-root 内，退出函数
    return;
  }

  // 获取鼠标的位置
  const mouseX = event.clientX + 10;
  const mouseY = event.clientY + 10;

  // 设置弹窗的位置
  // this.popupElement.style.left = `${mouseX + 10}px`;  // 让弹窗稍微偏离鼠标
  // this.popupElement.style.top = `${mouseY + 10}px`;

  if (selectedText.length > 0) {
    emitter.emit('content:float-selected', {
      value: selectedText,
      options: { mouseX, mouseY },
    });
  }
};

onMounted(() => {
  chrome.runtime.sendMessage(
    { action: 'CREATE_CHAT', data: 1 },
    function (response) {
      if (chrome.runtime.lastError) {
        console.error('Error:', chrome.runtime.lastError);
      } else {
        console.log('Received response:', response);
      }
    },
  );

  chrome.runtime.onMessage.addListener(function (request) {
    if (request.action === 'simulateTyping') {
      startTyping();
    }
  });

  addSelectionListener();
});

onUnmounted(() => {
  document.body.removeAttribute(EL_ATTR_NAME.showGrid);
  removeSelectionListener();
});
</script>
